﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using System.Web.Mvc;
using System.Web.Security;
using Bzure.Security;
using Bzure.Security.Permissions;
using Bzure.Security.Principal;
using Bzure.Apps.Security.ViewModels;
using Bzure.Common.Core;
using Bzure.Common.Text;
using Bzure.Apps.Security.ResourceFiles;


namespace Bzure.Apps.Security.Controllers
{
    [Export(typeof(IController)), ExportMetadata("Name", "User"), ExportMetadata("Area", "SecurityApp")]
    [Authorize]
    [SecurityAppAuthorize(RequiredRight = AdministrationRights.UserManage)]
    public class UserController : T4ViewController
    {
        MasterViewModel MasterViewModel = new ViewModels.MasterViewModel()
        {
            Title = "通用权限管理"
        };
        [SecurityAppFilter(PageControllerItems.UserListController)]
        public ActionResult UserList()
        {
            BzureUser[] users = Actor.Public.AsUserManager().GetAllUsers();
            ListUserViewModel ViewModel = new ListUserViewModel()
            {
                MasterViewModel = this.MasterViewModel,
                Title = "用户列表",
                Users = users,
                Url = Url.RouteUrl("SecurityApp_User", new { action = "DeleteUser" })
            };

            return Result(ViewModel);
        }
        [SecurityAppFilter(PageControllerItems.DeleteUserController)]
        public ActionResult DeleteUser(string id, FormCollection Collection)
        {
            BzureUser user = Actor.Public.AsUserManager().GetUserByID(id);
            NotificationViewModel notification = new NotificationViewModel();
            if (user.IsNotNull())
            {
                if (Actor.Public.AsUserManager().DeleteUserByID(id))
                {
                    notification.Data = NotificationData.YES;
                    notification.Content = string.Format("用户:{0}删除成功", user.UserName);
                    notification.NotificationType = NotificationType.Success;

                }
                else
                {
                    notification.Data = NotificationData.NO;
                    notification.Content = string.Format("用户:{0}删除失败", user.UserName);
                    notification.NotificationType = NotificationType.Error;

                }
            }
            else
            {
                notification.Data = NotificationData.NO;
                notification.Content = string.Format("用户ID:{0}不存在！", id);
                notification.NotificationType = NotificationType.Attention;
            }
            return Result(notification);
        }
        [SecurityAppFilter(PageControllerItems.AuthorizeUserController)]
        public ActionResult AuthorizeUser(string id)
        {
            BzureUser user = Actor.Public.AsUserManager().GetUserByID(id);
            if (user.IsNull())
            {
                return RedirectToAction("UserList");
            }
            AuthorizeUserViewModel ViewModel = new AuthorizeUserViewModel()
            {
                MasterViewModel = this.MasterViewModel,
                Title = "用户授权",
                Url = Url.RouteUrl("SecurityApp_User", new { action = "AuthorizeUser" }),
                UserName = user.UserName,
                UserState = user.State > 0,
                Roles = Actor.Public.AsRoleManager().GetAllTeamRoles(),
                RIDs = Actor.Public.AsRoleManager().GetTeamRoleIDsByUserID(user.UserID.ToString())
            };

            return Result(ViewModel);

        }
        [HttpPost]
        [SecurityAppFilter(PageControllerItems.AuthorizeUserController)]
        public ActionResult AuthorizeUser(string id, string UserState, FormCollection Collection)
        {
            BzureUser user = Actor.Public.AsUserManager().GetUserByID(id);
            if (user.IsNull())
            {
                return RedirectToAction("UserList");
            }
            //创建新的角色用户对应关系
            List<string> Roles = new List<string>();
            foreach (string key in Collection.AllKeys.Where(m => m.StartsWith("Role_")))
            {
                string roleid = Collection[key];
                if (roleid.IsNotNull())
                {
                    Roles.Add(roleid);
                }
            }
            user.State = UserState.IsNullOrEmpty() ? 0 : 1;
            NotificationViewModel notification = new NotificationViewModel();
            Actor.Public.AuthorizeUser(user, Roles.ToArray(), (bool ok) =>
            {
                if (ok)
                {
                    notification.Data = NotificationData.YES;
                    notification.Content = string.Format("用户：{0}授权保存成功", user.UserName);
                    notification.NotificationType = NotificationType.Success;
                }
                else
                {
                    notification.Data = NotificationData.NO;
                    notification.Content = string.Format("用户：{0}授权保存失败", user.UserName);
                    notification.NotificationType = NotificationType.Error;
                }
            });

            return Result(notification);
        }
        [SecurityAppFilter(PageControllerItems.ResetPasswordController)]
        public ActionResult ResetPassword(string id)
        {
            BzureUser user = Actor.Public.AsUserManager().GetUserByID(id);
            if (user.IsNull())
            {
                return RedirectToAction("UserList");
            }
            ResetPasswordViewModel ViewModel = new ResetPasswordViewModel()
            {
                Title = "重置密码",
                MasterViewModel = this.MasterViewModel,
                UserName = user.UserName,
                Url = Url.RouteUrl("SecurityApp_User", new { action = "ResetPassword" })
            };
            return Result(ViewModel);
        }
        [HttpPost]
        [SecurityAppFilter(PageControllerItems.ResetPasswordController)]
        public ActionResult ResetPassword(string id, FormCollection Collection)
        {
            BzureUser user = Actor.Public.AsUserManager().GetUserByID(id);
            if (user.IsNull())
            {
                return RedirectToAction("UserList");
            }
            string password = Collection["NewPassword"];
            NotificationViewModel notification = new NotificationViewModel();
            notification.Data = NotificationData.NO;
            notification.Content = string.Format("用户：{0}密码重置失败", user.UserName);
            notification.NotificationType = NotificationType.Error;
            if (Actor.Public.AsAccountManager().SetPassword(user.UserName, Actor.Public.AsAccountManager().EncryptPassword(password)))
            {
                notification.Data = NotificationData.YES;
                notification.Content = string.Format("用户：{0}密码重置成功", user.UserName);
                notification.NotificationType = NotificationType.Success;
            }
            return Result(notification);
        }


        [SecurityAppFilter(PageControllerItems.ResetNickNameController)]
        public ActionResult ResetNickName()
        {
            if (!Actor.Public.IsAuthenticated)
                return RedirectToAction("UserList");
            BzureUser user = Actor.Me.AsBzurePrincipal().ToUserModel().Entity;
            if (user.IsNull())
            {
                return RedirectToAction("UserList");
            }
            ResetNickNameViewModel ViewModel = new ResetNickNameViewModel()
            {
                Title = "重置昵称",
                MasterViewModel = this.MasterViewModel,
                UserName = user.UserName,
                NickName = user.NickName,
                Url = Url.RouteUrl("SecurityApp_User", new { action = "ResetNickName", id = user.UserID })
            };
            return Result(ViewModel);
        }
        [HttpPost]
        [SecurityAppFilter(PageControllerItems.ResetNickNameController)]
        public ActionResult ResetNickName(string id, FormCollection Collection)
        {
            BzureUser user = Actor.Public.AsUserManager().GetUserByID(id);
            if (user.IsNull())
            {
                return RedirectToAction("UserList");
            }
            string newNickName = Collection["NewNickName"];
            string msg = string.Format("用户：{0}设置昵称：{1}失败", user.UserName, newNickName);
            if (Actor.Public.AsUserManager().ExistsNickName(newNickName))
            {
                msg = string.Format("用户：{0}设置昵称：{1}失败,因为昵称已经被占用", user.UserName, newNickName);
            }
            else
            {
                if (Actor.Public.AsUserManager().SetNickName(user.UserName, newNickName))
                {
                    msg = string.Format("用户：{0}昵称重置成功", user.UserName);
                }
                else
                {
                    msg = string.Format("用户：{0}设置昵称：{1}失败,可能是因为软件内部错误", user.UserName, newNickName);
                }
            }
            ResetNickNameViewModel ViewModel = new ResetNickNameViewModel()
            {
                Title = "重置昵称",
                MasterViewModel = this.MasterViewModel,
                UserName = user.UserName,
                Url = Url.RouteUrl("SecurityApp_User", new { action = "ResetNickName", id = user.UserID }),
                Message = msg
            };
            return Result(ViewModel);
        }
    }

}
